// pages/movies/movies.js
var util = require('../../utils/util.js');
var app=getApp();


Page({

  /**
   * 页面的初始数据
   */
  data: {
    containerShow:true,

    inTheaters:{},
    comingSoon:{},
    top250:{}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (event) {
    var inTheatersUrl = app.globalData.doubanBase +"/v2/movie/in_theaters?start=0&count=3";
    var comingSoonUrl=app.globalData.doubanBase+"/v2/movie/coming_soon?start=0&count=3";
    var top250Url=app.globalData.doubanBase+"/v2/movie/top250?start=0&count=3";

    this.getMovieListData(inTheatersUrl,'inTheaters','正在热映');
    this.getMovieListData(comingSoonUrl,'comingSoon','即将上映');
    this.getMovieListData(top250Url,'top250','豆瓣Top250');
  },


  //获得豆瓣数据
  getMovieListData:function(url,settedKey,categoryTitle){
    var that=this;
    wx.request({
      url:url,
      method:'GET',
      header:{
        "Content-type":"json"
      },
      success:function(res){
        console.log(res)
        that.processDoubanData(res.data,settedKey,categoryTitle)
      },
      fail:function(error){
        console.log(error);
      }
    })
  },


  //格式化豆瓣数据
  processDoubanData:function(moviesDouban,settedKey,categoryTitle){
    var that=this;
    var movies=[];
    for(var i in moviesDouban.subjects) {
      var subject = moviesDouban.subjects[i];
      var title=subject.title;

      //电影名超出省略
      if(title.length>=6){
        title=title.substring(0,6)+'...';
      }

      //[1,1,1,1,0]
      var temp={
        stars: util.convertToStarsArray(subject.rating.stars),
        title:title,
        average:subject.rating.average,
        coverageUrl:subject.images.large,
        movieId:subject.id
      }
      //电影item进入数组
      movies.push(temp);
    }
    var readyData={};
    readyData[settedKey]={
      categoryTitle:categoryTitle,
      movies:movies
    }
    this.setData(readyData,function(){
      console.log(that.data)
    });

  },

  //更多电影页面
  onMoreTap:function(event) {
    //target是当前点击的组件
    //currentTarget是当前事件获取的组件
    var category=event.currentTarget.dataset.category;
    console.log(category);
    wx.navigateTo({
      url:"more-movie/more-movie?category="+category
    })
  },

  //查看电影详情
  onMovieTap:function(event){
    var movieId=event.currentTarget.dataset.movieid;
    wx.navigateTo({
      url:"movie-detail/movie-detail?id="+movieId
    })
  }



})